package com.bungarus.client.busi;

import com.bungarus.busi.Callback;
import com.bungarus.codec.protobuf.MessageProtobuf;
import com.bungarus.model.MessageBuilder;
import com.bungarus.model.MessageType;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import org.apache.log4j.Logger;

import java.util.concurrent.atomic.AtomicInteger;


/**
 * Created by tang on 2018/11/11.
 */
public class ClientHandler extends ChannelInboundHandlerAdapter {
    private static Logger logger = Logger.getLogger(ClientHandler.class);

    private Callback<EndUser, EndUser> callback;
    public ClientHandler(Callback<EndUser, EndUser> callback) {
        this.callback = callback;
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        MessageProtobuf.Message message = (MessageProtobuf.Message)msg;
        MessageProtobuf.Header header = message.getHeader();
        MessageProtobuf.Body body = message.getBody();

        if(null != header && message.getHeader().getType() == MessageType.AUTH){
            callback.call(new EndUser(header.getFrom(), header.getTenantID(), header.getSessionId(), header.getToken()));
        }
        if(null != header && message.getHeader().getType() == MessageType.LOGOUT){
            callback.call(new EndUser(header.getFrom(), header.getTenantID(), "", ""));
        }


        if(body.getContent().contains(" >>> ") || body.getContent().contains("concurrent ")){
            System.err.println("********************** recv size: " + Counter.counter.incrementAndGet());
        }
        else {
            System.out.println("=========== recv: " + msg.toString());
        }

        ctx.writeAndFlush(MessageBuilder.buildAckMessage(message.getHeader().getId(), message.getHeader().getId2()));
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        logger.error("Connection terminated !!!");
        super.channelInactive(ctx);
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        cause.printStackTrace();
        logger.error("Connection terminated !");
        ctx.close();
    }

    public static class Counter {
        public final static AtomicInteger counter = new AtomicInteger(0);
    }
}
